from pyx_package.script import BaseBehavior
from pyx_package.ps_paramete import PsParameter

import time
import socket

PYX_MODULE_NAME = "TCP-Client"

class ScriptBehavior(BaseBehavior):

    def __init__(self) -> None:
        super().__init__()
        
        self.SetExeMode("process")

        #缓存数据
        self._recv_buffer = bytes()

        #当前客户端对象
        self._sock = None
        
        self.InitParams()

    def InitParams(self):

        #服务端地址
        self.p_host = self.CreateParam("host", "服务端地址", PsParameter.Input, str, "127.0.0.1")

        #服务端端口
        self.p_port = self.CreateParam("port", "服务端端口", PsParameter.Input, int, 8080)

        #发送的数据
        self.p_send_data = self.CreateParam("send data", "发送的数据", PsParameter.Input, bytes, bytes())

        #接收到的数据
        self.p_recv_data = self.CreateParam("recv data", "接受到的数据", PsParameter.Output, bytes)

        #每次接受数据的大小
        self.p_recv_length = self.CreateParam("recv length", "每次接受数据的大小", PsParameter.Input, int, 1024)

    def Start(self):

        self._sock = socket.socket()

        host = self.p_host.value
        port = self.p_port.value

        #循环尝试重复链接
        is_connect = False

        while not is_connect:
            try:
                self._sock.connect((host, port))
                is_connect = True
            except:
                pass

            time.sleep(0.5)
            
        self.Debug("服务器链接成功", "success")

        while 1:

            buffer = self._sock.recv(self.p_recv_length.value)
            self._recv_buffer += buffer
            self.Ready()


    def DoStep(self):
    
        self.p_recv_data.value = self._recv_buffer
        self._recv_buffer = bytes()

    def ParamChanged(self, ident, value):
        super().ParamChanged(ident, value)

        if ident == "send data":
            self._sock.send(value)
            